package com.ihr360.authority.sharing.privilege;

import com.ihr360.authority.sharing.annonation.AccessControl;
import com.ihr360.authority.sharing.service.AuthUserResourceService;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.validation.ValidationUtils;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractBizClassPrivilege<ID> {
    protected String method;
    protected Integer privilege;
    protected Integer publicity;
    protected boolean accessControl;
    protected AuthUserResourceService authUserResourceService;
    protected IAccessControlClass iAccessControlClass;
    protected Map<ID, Integer> userResourcesPrivilege;
    protected Map<ID, Integer> userResourcesPublicity;

    public AbstractBizClassPrivilege(IAccessControlClass iAccessControlClass) {
        this.iAccessControlClass = iAccessControlClass;
    }

    public Map<ID, Integer> getUserResourcesPrivilege() {
        return userResourcesPrivilege;
    }

    public Map<ID, Integer> getUserResourcesPublicity() {
        return userResourcesPublicity;
    }

    public boolean noAccessControl(String method) {
        ValidationUtils.rejectIfEmpty(iAccessControlClass, null, "无法获取权限控制目标类");
        AccessControl annotation = AnnotationUtils.findAnnotation(iAccessControlClass.getServiceClass(), AccessControl.class);
        if (annotation == null) {
            // 默认控制
            return false;
        }
        if (annotation.disableAll()) {
            return true;
        }
        String[] nacl = annotation.nacl();
        return CollectionUtils.contains(nacl, method);
    }

    public String toStringId(ID id) {
        String strId = null;
        if (id instanceof Long) {
            strId = String.valueOf(id);
        } else if (id instanceof String) {
            strId = (String) id;
        } else {
            strId = id.toString();
        }
        return strId;
    }

    public ID toID(Object obj){
        return (ID)obj;
    }

    public void toIDKeyMap(Map<Object, Integer> privilegeMap, Map<Object, Integer> publicityMap) {
        if (CollectionUtils.isEmpty(privilegeMap)) {
            userResourcesPrivilege = null;
        } else {
            userResourcesPrivilege = new HashMap<>(privilegeMap.size());
            privilegeMap.forEach((key, value) -> userResourcesPrivilege.put(toID(key), value));
        }
        if (CollectionUtils.isEmpty(publicityMap)) {
            userResourcesPublicity = null;
        } else {
            userResourcesPublicity = new HashMap<>(publicityMap.size());
            publicityMap.forEach((key, value) -> userResourcesPublicity.put(toID(key), value));
        }
    }

}